package it.unibo.android.location;
import java.text.NumberFormat;
import java.util.Date;

import it.unibo.location.ILocation;

/**
 * @author ale
 * @version 1.0
 * @created 24-ott-2012 00:45:22
 */
public class AndroidLocation implements ILocation {

	private double latitude;
	private double longitude;
	private double altitude;
	private float accuracy;
	private long sampleTime;

	public AndroidLocation(double latitude, double longitude, double altitude){
		this.latitude = latitude;
		this.longitude = longitude;
		this.altitude = altitude;
		this.accuracy = (float)0.1;
		Date now = new Date();
		this.sampleTime = now.getTime();
	}

	@Override
	public double getLatitude() {
		return latitude;
	}

	@Override
	public double getLongitude() {
		return longitude;
	}

	@Override
	public double getAltitude() {
		return altitude;
	}

	@Override
	public float distanceTo(ILocation location) {
		if(location == null)
			return 0;
		
		return distFrom(this.latitude, this.longitude, location.getLatitude(), location.getLongitude());
	}

	@Override
	public float getAccuracy() {
		return accuracy;
	}

	@Override
	public long getSampleTime() {
		return sampleTime;
	}

	private static float distFrom(double lat1, double lng1, double lat2, double lng2) {
		double earthRadius = 6371000; // m
		double dLat = Math.toRadians(lat2-lat1);
		double dLng = Math.toRadians(lng2-lng1);
		double sindLat = Math.sin(dLat / 2);
		double sindLng = Math.sin(dLng / 2);
		double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
				* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		double dist = earthRadius * c;

		return (float)dist;
	}
	
	@Override
	public String toString() 
	{
		NumberFormat formatter = NumberFormat.getInstance();
		formatter.setMaximumFractionDigits(4);
		return "Lat: " + formatter.format(latitude) + " Long: " + formatter.format(longitude) + " Alt: " + formatter.format(altitude);
	}
}